<template>
  <div class="inspection-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 24px;">
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#3a84ff"><Monitor /></el-icon>
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总计</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#67c23a"><CircleCheck /></el-icon>
          <div class="stat-value" style="color: #67c23a;">{{ stats.healthy }}</div>
          <div class="stat-label">健康</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#e6a23c"><Warning /></el-icon>
          <div class="stat-value" style="color: #e6a23c;">{{ stats.warning }}</div>
          <div class="stat-label">警告</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#f56c6c"><CircleClose /></el-icon>
          <div class="stat-value" style="color: #f56c6c;">{{ stats.critical }}</div>
          <div class="stat-label">严重</div>
        </div>
      </el-col>
    </el-row>

    <!-- 操作区 -->
    <div class="dashboard-card" style="padding: 20px;">
      <div class="card-header">
        <h3>系统巡检报告</h3>
        <div class="header-actions">
          <el-switch
            v-model="autoAlert"
            active-text="自动告警"
            inactive-text=""
            style="margin-right: 15px;"
          />
          <el-button type="primary" @click="startInspection" :loading="loading">
            <el-icon><Refresh /></el-icon> {{ loading ? '巡检中...' : '开始巡检' }}
          </el-button>
          <el-button type="success" @click="showEmailDialog" :disabled="!inspectionData.length">
            <el-icon><Message /></el-icon> 发送邮件
          </el-button>
        </div>
      </div>

      <!-- 巡检时间 -->
      <div v-if="lastInspectionTime" class="inspection-time">
        <el-icon><Clock /></el-icon>
        <span>最后巡检时间: {{ lastInspectionTime }}</span>
      </div>

      <!-- 巡检表格 -->
      <el-table :data="inspectionData" style="width: 100%; margin-top: 20px;" v-loading="loading">
        <el-table-column prop="hostname" label="主机名" width="140" />
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="server_type" label="服务器类型" width="120" />
        <el-table-column prop="host_group" label="主机组" width="100" />
        
        <el-table-column label="CPU" width="100">
          <template #default="{ row }">
            <span v-if="row.cpu_usage !== undefined">{{ row.cpu_usage }}%</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="内存" width="120">
          <template #default="{ row }">
            <div v-if="row.mem_usage !== undefined">
              <div>{{ row.mem_usage }}%</div>
              <div style="font-size: 11px; color: #909399;">{{ row.mem_used }}/{{ row.mem_total }}</div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="磁盘" width="120">
          <template #default="{ row }">
            <div v-if="row.disk_usage !== undefined">
              <div>{{ row.disk_usage }}%</div>
              <div style="font-size: 11px; color: #909399;">{{ row.disk_used }}/{{ row.disk_total }}</div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="网络(收/发)" width="130">
          <template #default="{ row }">
            <span v-if="row.net_recv">{{ row.net_recv }}/{{ row.net_sent }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="负载" width="80">
          <template #default="{ row }">
            <span v-if="row.load_avg">{{ row.load_avg }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'healthy'" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="row.status === 'warning'" type="warning" size="small">警告</el-tag>
            <el-tag v-else-if="row.status === 'critical'" type="danger" size="small">严重</el-tag>
            <el-tag v-else type="info" size="small">错误</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="问题" min-width="200">
          <template #default="{ row }">
            <div v-if="row.issues && row.issues.length">
              <div v-for="(issue, index) in row.issues" :key="index" class="issue-text">
                <el-icon color="#f56c6c"><WarningFilled /></el-icon>
                {{ issue }}
              </div>
            </div>
            <span v-else style="color: #909399;">无</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 发送邮件对话框 -->
    <el-dialog v-model="emailDialogVisible" title="发送巡检报告" width="500px">
      <el-form label-width="100px">
        <el-form-item label="收件人">
          <el-select 
            v-model="selectedEmails" 
            multiple 
            filterable 
            allow-create 
            default-first-option
            placeholder="请选择或输入邮箱地址"
            style="width: 100%;"
          >
            <el-option-group label="收件人列表">
              <el-option 
                v-for="recipient in recipients" 
                :key="'recipient-' + recipient.id" 
                :label="`${recipient.name} (${recipient.email})`" 
                :value="recipient.email"
              >
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ recipient.name }}</span>
                  <span style="font-size: 12px; color: #909399;">{{ recipient.email }}</span>
                </div>
              </el-option>
            </el-option-group>
            <el-option-group label="系统用户">
              <el-option 
                v-for="user in users" 
                :key="'user-' + user.id" 
                :label="`${user.username} (${user.email})`" 
                :value="user.email"
                :disabled="!user.email"
              />
            </el-option-group>
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            💡 可直接输入邮箱地址并回车添加，支持多个收件人
          </div>
          <div v-if="selectedEmails.length > 0" style="color: #67c23a; font-size: 12px; margin-top: 5px;">
            ✓ 已选择 {{ selectedEmails.length }} 个收件人
          </div>
        </el-form-item>
        
        <el-form-item label="巡检摘要">
          <div class="email-summary">
            <p>总计: {{ inspectionData.length }} 台主机</p>
            <p style="color: #67c23a;">健康: {{ stats.healthy }} 台</p>
            <p style="color: #e6a23c;">警告: {{ stats.warning }} 台</p>
            <p style="color: #f56c6c;">严重: {{ stats.critical }} 台</p>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendEmail" :loading="sendingEmail">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { inspectionAPI, recipientAPI } from '@/api'
import axios from 'axios'

const loading = ref(false)
const inspectionData = ref([])
const lastInspectionTime = ref('')
const stats = reactive({
  total: 0,
  healthy: 0,
  warning: 0,
  critical: 0,
  error: 0
})

const emailDialogVisible = ref(false)
const selectedEmails = ref([])
const sendingEmail = ref(false)
const users = ref([])
const recipients = ref([]) // 收件人列表
const autoAlert = ref(true) // 默认开启自动告警
const alertEmailList = ref([]) // 告警邮件列表

// 开始巡检
const startInspection = async () => {
  loading.value = true
  try {
    const result = await inspectionAPI.getInspectionData()
    
    stats.total = result.total
    stats.healthy = result.healthy
    stats.warning = result.warning
    stats.critical = result.critical
    stats.error = result.error
    
    inspectionData.value = result.data
    lastInspectionTime.value = new Date().toLocaleString()
    
    ElMessage.success('巡检完成！')
    
    // 自动告警检查
    if (autoAlert.value && (stats.warning > 0 || stats.critical > 0)) {
      checkAndSendAlert()
    }
  } catch (error) {
    ElMessage.error('巡检失败')
    console.error('巡检失败:', error)
  } finally {
    loading.value = false
  }
}

// 检查并发送告警
const checkAndSendAlert = async () => {
  // 获取所有管理员邮箱
  const adminEmails = users.value
    .filter(user => user.email && (user.is_staff || user.is_superuser))
    .map(user => user.email)
  
  if (!adminEmails.length) {
    ElMessage.warning('未找到管理员邮箱，无法发送告警')
    return
  }
  
  // 过滤出有问题的主机
  const problemHosts = inspectionData.value.filter(host => 
    host.status === 'warning' || host.status === 'critical'
  )
  
  if (!problemHosts.length) {
    return
  }
  
  // 显示告警通知
  ElMessage({
    message: `检测到 ${problemHosts.length} 台主机存在异常，正在发送告警邮件...`,
    type: 'warning',
    duration: 3000
  })
  
  try {
    await inspectionAPI.sendEmail({
      recipients: adminEmails,
      data: inspectionData.value,
      alert: true // 标记为告警邮件
    })
    
    ElMessage.success(`告警邮件已发送至 ${adminEmails.length} 位管理员`)
  } catch (error) {
    console.error('告警邮件发送失败:', error)
    ElMessage.error('告警邮件发送失败')
  }
}

// 获取用户列表（用于邮箱选择）
const fetchUsers = async () => {
  try {
    const token = localStorage.getItem('access_token')
    const response = await axios.get('/api/users/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    users.value = response.data.results || response.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取收件人列表
const fetchRecipients = async () => {
  try {
    const data = await recipientAPI.list({ is_active: true })
    recipients.value = data.results || data || []
  } catch (error) {
    console.error('获取收件人列表失败:', error)
  }
}

// 显示发送邮件对话框
const showEmailDialog = () => {
  if (!inspectionData.value.length) {
    ElMessage.warning('请先进行系统巡检')
    return
  }
  emailDialogVisible.value = true
}

// 验证邮箱格式
const validateEmails = (emails) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  const invalidEmails = []
  
  for (const email of emails) {
    if (!emailRegex.test(email)) {
      invalidEmails.push(email)
    }
  }
  
  return {
    valid: invalidEmails.length === 0,
    invalidEmails
  }
}

// 发送邮件
const sendEmail = async () => {
  if (!selectedEmails.value.length) {
    ElMessage.warning('请选择收件人')
    return
  }
  
  // 验证邮箱格式
  const validation = validateEmails(selectedEmails.value)
  if (!validation.valid) {
    ElMessage.error(`邮箱格式不正确：${validation.invalidEmails.join(', ')}`)
    return
  }
  
  sendingEmail.value = true
  try {
    await inspectionAPI.sendEmail({
      recipients: selectedEmails.value,
      data: inspectionData.value
    })
    
    ElMessage.success('邮件发送成功')
    emailDialogVisible.value = false
    // 发送成功后清空选择
    selectedEmails.value = []
  } catch (error) {
    const errorMsg = error.response?.data?.error || '邮件发送失败'
    ElMessage.error(errorMsg)
  } finally {
    sendingEmail.value = false
  }
}

onMounted(() => {
  fetchUsers()
  fetchRecipients()
})
</script>

<style scoped>
.inspection-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header h3 {
  margin: 0;
  color: #3a84ff;
  font-size: 20px;
}

.inspection-time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.issue-text {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: 4px;
}

.email-summary {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.8;
}

.email-summary p {
  margin: 5px 0;
}
</style>
